package com.renwei.yunlong.activity.news;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.CommonSearchActivity;
import com.renwei.yunlong.activity.contacts.SeeContactsByDepartmentActivity;
import com.renwei.yunlong.activity.contacts.SeeContactsByEnterpriseActivity;
import com.renwei.yunlong.activity.contacts.SeeContactsByFuctionActivity;
import com.renwei.yunlong.adapter.SortContactAdapter;
import com.renwei.yunlong.adapter.StartChatListAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.EmpInfoJsonBean;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.bean.contacts.ContactsBean;
import com.renwei.yunlong.event.ChatListCloseEvent;
import com.renwei.yunlong.event.ContactCheckEvent;
import com.renwei.yunlong.fragment.ContactsFragment;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.ContactPingyinComparator;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.PinyinUtils;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UtilList;
import com.renwei.yunlong.view.SearchImage;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class StartChatActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {

    private static final int from_type = 1;
    private List<Contact> contactList;
    private ContactPingyinComparator contactPingyinComparator;
    private SortContactAdapter contactAdapter;
    private View HeaderView;
    private SimpleOptionView simpleTileView;
    private SearchImage searchImage;
    private ListView clvContactList;
    private Button btnCommit;
    private RecyclerView rlvBottomContact;
    private StartChatListAdapter bottomListAdapter;
    private String groupId;

    /**
     * 判断是消息页面条转过来的 还是从追加群成员页面跳转过里啊的
     *
     * @param context 对象页面
     * @param groupId 群Id
     */
    public static void openActivity(Context context, String groupId) {
        Intent intent = new Intent(context, StartChatActivity.class);
        intent.putExtra("groupId", groupId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        setContentView(R.layout.activity_start_chat);
        groupId = StringUtils.value(getIntent().getStringExtra("groupId"));
        TranspaintActivity.setGroupId(groupId);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        simpleTileView = (SimpleOptionView) findViewById(R.id.simpleTileView);
        searchImage = (SearchImage) findViewById(R.id.search_image);
        searchImage.setOnClickListener(this);
        clvContactList = (ListView) findViewById(R.id.clv_contact_list);
        btnCommit = (Button) findViewById(R.id.btn_commit);
        btnCommit.setOnClickListener(this);
        rlvBottomContact = (RecyclerView) findViewById(R.id.rlv_bottom_contact);
        HeaderView = LayoutInflater.from(this).inflate(R.layout.contact_head, null);
        HeaderView.findViewById(R.id.rl_department).setOnClickListener(this);
        HeaderView.findViewById(R.id.rl_function).setOnClickListener(this);
        HeaderView.findViewById(R.id.rl_friends).setOnClickListener(this);
        clvContactList.addHeaderView(HeaderView);
        contactList = new ArrayList<>();
        // 实例化汉字转拼音类
        contactPingyinComparator = new ContactPingyinComparator();
        rlvBottomContact.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        bottomListAdapter = new StartChatListAdapter(this, companyType);
        contactAdapter = new SortContactAdapter(this, from_type, companyType, contactList);
        clvContactList.setAdapter(contactAdapter);
        rlvBottomContact.setAdapter(bottomListAdapter);
        if ("".equals(StringUtils.value(groupId))) {// : 2017/12/10 如果是从创建群组添加页面条转过来则不清空原来列表
            simpleTileView.setTitle("发起会话");
        } else {
            simpleTileView.setTitle("添加群成员");
        }
        requestAllContactInfo();
        initBottomContactList();
    }

    //  2017/12/8 11:17  查询所有的联系人信息
    private void requestAllContactInfo() {
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        String json = "";
        if ("1".equals(companyType)) {
            json = new Gson().toJson(new EmpInfoJsonBean(ownerBean.getRows().getEmployeeId(), "", 1, 1000));
        } else if ("2".equals(companyType)) {
            json = new Gson().toJson(new EmpInfoJsonBean(serviceLoginBean.getRows().getEmployeeId(), "", 1, 1000));
        }
        manager.queryContactByCharacter(this, json, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_department://部门
                SeeContactsByDepartmentActivity.openactivity(this, from_type);
                break;
            case R.id.rl_function://职能
                SeeContactsByFuctionActivity.OpenActivity(this, from_type);
                break;
            case R.id.rl_friends://好友
                SeeContactsByEnterpriseActivity.OpenActivity(this, from_type);
                break;
            case R.id.btn_commit://发送创建或者追加群成员消息
                TranspaintActivity.openActivity(this);
                break;
            case R.id.search_image:
                CommonSearchActivity.OpenActivityFromContact(this, v, ContactsFragment.class, 999, from_type, companyType);
                break;
            default:
                break;
        }
    }


    /**
     * 为列表填充数据
     *
     * @param contactList
     * @return
     */
    //转拼音
    private List<Contact> filledPingYing(List<Contact> contactList) {
        for (int i = 0; i < UtilList.getCount(contactList); i++) {
            Contact appEmployee = contactList.get(i);
            if (appEmployee != null) {
                String name = appEmployee.getName();
                //汉字转换成拼音
                String pinyin = PinyinUtils.getPingYin(name);
                String sortString = pinyin.substring(0, 1).toUpperCase();
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    appEmployee.setLetter(sortString.toUpperCase());
                } else {
                    appEmployee.setLetter("#");
                }
            }

        }
        return contactList;
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefreshName(ContactCheckEvent event) {
        initBottomContactList();
        if (contactAdapter != null) {
            contactAdapter.notifyDataSetChanged();
        }
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onClosePage(ChatListCloseEvent event) {
        finish();
    }

    public void initBottomContactList() {
        bottomListAdapter.setData(AppHelper.getCheckContactList());
        String commitText = "";
        if (UtilList.getCount(AppHelper.getCheckContactList()) == 0) {
            commitText = "确定";
        } else {
            commitText = "确定(" + UtilList.getCount(AppHelper.getCheckContactList()) + ")";
        }
        btnCommit.setText(commitText);
    }


    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1://查询联系人信息接口
                ContactsBean bean = new Gson().fromJson(result, ContactsBean.class);
                int code = bean.getMessage().getCode();
                if (code == 200) {
                    contactList = filledPingYing(bean.getRows());
                    // 根据a-z进行排序源数据
                    Collections.sort(contactList, contactPingyinComparator);
                    contactAdapter.refresh(contactList);
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        LogUtil.e(code);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onBackPressed() {
        AppHelper.clearCheckList();// : 2017/12/13 返回的时候清空选中列表
        super.onBackPressed();
    }
}
